package stage_1_module_4.code.homework_1;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

public class Model {
    private static String filename = "./stage_1_module_4/code/homework_1/student.txt";

    public static void showStudent(List<Student> sl) {
        System.out.println(sl);
    }

    public static void addStudent(List<Student> sl, Student a) {
        sl.add(a);
    }

    public static Student findStudentByNo(List<Student> sl, String no) {
        for (Student st : sl) {
            if (st.getNo().equals(no)) {
                return st;
            }
        }
        return null;
    }

    public static void removeStudentByNo(List<Student> sl, String no) {
        boolean hasFind = false;
        int i = 0;
        for (Student st : sl) {
            if (st.getNo().equals(no)) {
                i = sl.indexOf(st);
                hasFind = true;
            }
        }
        if (hasFind) {
            sl.remove(i);
        }
    }

    public static void updateStudent(List<Student> sl, Student u) {
        for (Student st : sl) {
            if (st.getNo().equals(u.getNo())) {
                int i = sl.indexOf(st);
                sl.set(i, u);
                break;
            }
        }
    }

    public static void saveList(List<Student> sl) {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(filename));
            oos.writeObject(sl);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    }

    public static Object readList() {
        ObjectInputStream ois = null;
        Object obj = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(filename));
            obj = ois.readObject();
            // if (ois instanceof List) {
            //     List<Student> sl = (List<Student>) ois.readObject();
            // }
            // return sl;

        } catch (IOException | ClassNotFoundException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } finally {
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return obj;
        }
    }
}
